package com.example.service.impl;

import com.example.pojo.LoginUser;
import com.example.pojo.ResponseResult;
import com.example.pojo.Users;
import com.example.service.LoginService;
import com.example.utils.JwtUtil;
import com.example.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/*
 *  @author 雨安
 *  类名： LoginServiceImpl
 *  创建时间：2024/3/18
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Override
    public ResponseResult login(Users user) {
        //封装账号密码 下方实现类封装的对象
        UsernamePasswordAuthenticationToken
                //传入账号密码
                authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());
        //AuthenticationManager进行用户认证
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        //如果认证未通过，给出对应的提示
        if (Objects.isNull(authenticate)){
            //为null抛出异常
            throw new RuntimeException("认证未通过,登录失败!");
        }
        //如果认证通过了，使用userid生成一个jwt，jwt存入ResponseResult返回
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        //获取用户Id
        String uid = loginUser.getUser().getUid().toString();
        //生成jwt
        String jwt = JwtUtil.createJWT(uid);
        //把完整的用户信息存入redis userid作为key
        Map<String,String> map = new HashMap<>();
        //放入token
        map.put("token",jwt);
        //存入redis
        redisCache.setCacheObject("login:"+uid,loginUser);
        //返回map
        return new ResponseResult(200,"登录成功",map);
    }

    @Override
    public ResponseResult logout() {
        //获取SecurityContextHolder用户id 拿到登录存储的对象
        UsernamePasswordAuthenticationToken authentication
                = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        //获取用户信息,封装于实现UserDetails的类强转成
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        //拿到用户id
        Long uid = loginUser.getUser().getUid();
        //删除Redis种的值
        redisCache.deleteObject("login:"+uid);
        //返回影响
        return new ResponseResult(200,"注销成功",null);
    }
}
